<template>
  <div class="agentTree">
    <div class="companyName clearfix" @click="allClick" :style="{background: !isShowHighlight ? '#F3FAFF' : ''}">
      <div class="contentText fl">
        {{companyName}}
      </div>
      <el-dropdown class="fr dropDown" trigger="click" placement="bottom-start" @command="(command)=>{commandChange(command, '')}">
        <div class="moreBtn" @click="click">
          <span class="el-icon-more"></span>
        </div>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="add">
            <span class="V7_iconfont V7_iconV7tubiao_tianjia"></span>
            添加部门</el-dropdown-item>
          <el-dropdown-item command="import">
            <span class="V7_iconfont V7_iconV7tubiao_daoru"></span>
            导入</el-dropdown-item>
          <el-dropdown-item command="export">
            <span class="V7_iconfont V7_iconV7tubiao_shangchuan-97"></span>
            导出</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <el-tree
      :data="schemaData"
      :props="defaultProps"
      @node-click="handleNodeClick"
      :expand-on-click-node="false"
      :highlight-current="isShowHighlight"
      :default-expand-all="true">
      <span class="custom-tree-node clearfix" slot-scope="{ node, data }">
         <span class="contentText fl">
          {{ node.label }}
        </span>
        <el-dropdown v-if="node.level <= 15" class="fr dropDown" trigger="click" placement="bottom-start" @command="(command)=>{commandChange(command, data._id, node)}">
          <span class="moreBtn" @click="click">
            <span class="el-icon-more"></span>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="add">
              <span class="V7_iconfont V7_iconV7tubiao_tianjia"></span>
              添加部门</el-dropdown-item>
            <el-dropdown-item command="edit">
              <span class="V7_iconfont V7_iconV7tubiao_xianbianji"></span>
              编辑部门</el-dropdown-item>
            <el-dropdown-item command="export">
              <span class="V7_iconfont V7_iconV7tubiao_shangchuan-97"></span>
              导出</el-dropdown-item>
            <el-dropdown-item divided command="del">
              <span class="V7_iconfont V7_iconV7tubiao_shanchu"></span>
              删除</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </span>
    </el-tree>
    <drawer
      class="agent-drawer"
      direction="rtl"
      :title="drawer.title"
      :drawer="drawer.isShow"
      @save="confirm"
      @cancelFun="cancelFun('addOrEdit')"
      @closeDraw="cancelFun('addOrEdit')">
      <template slot="column">
        <div class="agent-contain-box">
          <el-form class="m7-form form" :rules="rules" ref="form"
            size="mini" :model="form" label-position="top">
            <el-form-item label="部门名称" prop="name">
              <el-input v-model="form.name" size="mini" :maxlength="32"></el-input>
            </el-form-item>
            <el-form-item label="上级部门" prop="parentIdList">
              <el-cascader
                v-model="form.parentIdList"
                :options="schemaData"
                :props="{ checkStrictly: true, label: 'name', children: 'children', value: '_id' }"
                clearable>
              </el-cascader>
            </el-form-item>
          </el-form>
        </div>
      </template>
    </drawer>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import { organizationConfigModule } from '@/store/modules/config/organizationConfig/index'
import drawer from '@/common/views/drawer/index.vue'
import { Form as ElForm } from 'element-ui'
function handleTreeData (treeData: any, arr: any) {
  if (treeData) {
    arr.unshift(treeData.data._id)
    if (treeData.data && treeData.data.parentId) {
      handleTreeData(treeData.parent, arr)
    }
  }
}
@Component({
  name: 'agentTree',
  components: {
    drawer
  }
})
export default class AgentTree extends Vue {
  @Prop() private schemaData: any
  @Prop() private companyName: string | undefined
  private $confirm: any
  private $message: any
  private $router: any

  private currentId: string = ''

  private isShowHighlight = false

  private drawer = {
    title: '添加部门',
    isShow: false
  }

  private form: any = {
    name: '',
    parentIdList: []
  }

  private rules = {
    name: [{ required: true, message: '请填写部门', trigger: 'blur' }]
  }

  private defaultProps = {
    label: 'name',
    children: 'children'
  }

  private click ($event) {
    $event.stopPropagation()
  }

  private allClick () {
    this.form.parentIdList = ''
    this.isShowHighlight = false
    this.$emit('handleNodeClick', '')
  }

  private handleNodeClick (data: any, node: any) {
    this.isShowHighlight = true
    this.$emit('handleNodeClick', node.data._id)
  }

  private commandChange (val: any, row: any, node: any) {
    const newParentId: any = []
    const exportData: any = {
      url: '/base/action/department/export',
      method: 'post',
      data: { departmentId: row }
    }
    switch (val) {
      case 'add' :
        this.drawer.isShow = true
        this.form.name = ''
        this.drawer.title = '添加部门'
        handleTreeData(node, newParentId)
        this.form.parentIdList = newParentId
        this.currentId = ''
        break
      case 'edit' :
        this.drawer.isShow = true
        this.drawer.title = '编辑部门'
        this.currentId = row
        this.form.name = node.data.name
        handleTreeData(node, newParentId)
        newParentId.pop()
        this.form.parentIdList = newParentId
        break
      case 'import' :
        this.$emit('import')
        break
      case 'export' :
        organizationConfigModule.organizationCommonAction(exportData).then(res => {
          if (res && res.success) {
            const h = this.$createElement
            this.$message({
              message: h('div', { style: 'color:#2ed47a' }, [
                h('span', {}, `导出任务${res.data.taskId || ''}进入排队，请前往`),
                h('a', { on: { click: this.jumpToTransmissionCenter }, style: 'cursor:pointer,color:#008cee' }, '传输中心'),
                h('span', {}, '查看')
              ]),
              type: 'success',
              duration: 5000
            })
          }
        })
        break
      case 'del' :
        this.$confirm('删除部门后，此部门现有座席的部门将清空，需要重新设置。请谨慎操作', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const actionData = {
            url: '/base/action/department/remove',
            method: 'post',
            data: { _id: row }
          }
          organizationConfigModule.organizationCommonAction(actionData).then(res => {
            if (res && res.success) {
              this.$emit('delFun')
              this.$message({ type: 'success', message: '删除成功!' })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
        break
    }
  }

  private jumpToTransmissionCenter () {
    this.$router.push('/transmission_center/index/tx_export_task?taskModule=department')
  }

  private cancelFun () {
    this.drawer.isShow = false
    this.form.name = ''
  }

  private confirm () {
    const formRef = this.$refs.form as ElForm
    formRef.validate(valide => {
      if (valide) {
        const actionData = {
          url: '/base/action/department/create',
          method: 'post',
          data: { ...this.form }
        }
        if (this.currentId) {
          actionData.url = '/base/action/department/update'
          actionData.data._id = this.currentId
          if (this.form.parentIdList.lenght > 0 && this.currentId === this.form.parentIdList[this.form.parentIdList.length - 1]) {
            this.$message.error('上级部门不能是当前部门')
            return false
          }
        }
        organizationConfigModule.organizationCommonAction(actionData).then(res => {
          if (res && res.success) {
            this.$message.success(`${this.currentId ? '编辑' : '添加'}部门成功`)
            this.$emit('editOrAdd')
            this.drawer.isShow = false
          }
        })
      }
    })
  }

  // private getTreeData () {
  //   const actionData = {
  //     url: '/base/action/department/query',
  //     method: 'post',
  //     data: {}
  //   }
  //   organizationConfigModule.organizationCommonAction(actionData).then(res => {
  //     if (res && res.success && res.data) {
  //       this.schemaData = res.data.tree || []
  //       this.companyName = res.data.companyName || ''
  //     }
  //   })
  // }
}
</script>
<style lang="stylus" scoped>
  .agentTree
    height 100%
    width 100%
    // overflow auto
    .companyName
      height 40px
      line-height 40px
      cursor pointer
      padding-left 10px
    .custom-tree-node
      width 100%
      line-height 40px
      height 40px
      display inline-block
    .contentText
      width calc(100% - 28px)
      overflow hidden
      text-overflow ellipsis
      white-space nowrap
    .moreBtn
      width 20px
      height 20px
      display inline-block
      background #DCEBF5
      border-radius 3px
      text-align center
      line-height 20px
    .el-icon-more
      color #303753
    .companyName:hover
      background #F3FAFF
    .companyName:hover .dropDown
      visibility visible
    .custom-tree-node:hover .dropDown
      visibility visible
    .dropDown
      visibility hidden
      margin-right 5px
  .V7_iconfont
    font-size 12px
    visibility middle
    color #B3B9C7
  .el-dropdown-menu__item:hover .V7_iconfont
    color #008cee
</style>
<style lang="stylus">
  .agentTree
    .el-tree
      width max-content
      min-width 167px
    .el-tree-node__content
      height 40px
    .el-tree-node__content:hover
      background #F3FAFF
    .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content
      background #F3FAFF
    .el-cascader
      width 100%
    .el-tree-node > .el-tree-node__children
      overflow visible
</style>
